#include "push.h"
Stack top = NULL;
Stack base = NULL;

Stack alloc()
{
  Stack p = (Stack) malloc(sizeof(struct stack));
  memset(p,0,sizeof(struct stack));
  p -> s = NULL;
  p -> prev = NULL;
  return p;
}

void push(char *s)
{
  if(top == NULL)  
    {
      top = alloc();
      top -> s = s;
      return;
    }

  Stack node = alloc();
  node -> s = s;
  node -> prev = top;
  top = node;
}

char* pop()
{
  char* p;
  Stack st;
  if(top == NULL) 
    {
      return NULL;
    }
  if(top -> prev == NULL)   
    {
      p = top -> s ;
      free(top);
      top = NULL;
      return p;
    }

  st = top -> prev; 
  p = top -> s;
  free(top);
  top = st;
  return p;
}

void cleanStack()
{
  char *p;

  do
    {
      p = pop();
      if(p == NULL)
        break;
    }while(1);
}

void PrintStatement()
{
  char prefix[1000] = "";
  memset(prefix,0,1000*sizeof(char));
  const char *start = "if(%s != null)\n{\n";
  const char *end1 = "%s.Dispose();\n";
  const char *end2 = "%s = null;\n}\r\n";
  char *t1;
  char *name = pop();  
  char *type = pop();

  if(strcmp(type,"RadContextMenu") == 0
     || strcmp(type,"RadMenuItem") == 0
     ) 
    {
      t1 = "if(%s.DropDown != null && %s.DropDown.Items != null)\n%s.DropDown.Items.Clear();\n";
      sprintf(prefix,"%s %s %s %s",start,t1,end1,end2);
      printf(prefix,name,name,name,name,name,name);
    }
  else if(strcmp(type,"DataTable") == 0
          ||strcmp(type,"DataSet") == 0
          )
    {
      t1 = "%s.Clear();\n";
      sprintf(prefix,"%s %s %s %s",start,t1,end1,end2);
      printf(prefix,name,name,name,name);
    }
  else if(strcmp(type,"Dictionary") == 0
          ||strcmp(type,"List") == 0
          )
    {
      t1 = "%s.Clear();\n";
      sprintf(prefix,"%s %s %s",start,t1,end2);
      printf(prefix,name,name,name,name);
    }
  else if(strcmp(type,"RadGridView") == 0
          )
    {
      t1 = "DataTable dt = %s.DataSource as DataTable;\nif (dt != null)\ndt.Clear();\n";
      sprintf(prefix,"%s %s %s %s",start,t1,end1,end2);
      printf(prefix,name,name,name,name);
    }
/*   else if(strcmp(type,"RadListControl") == 0|| */
/*           strcmp(type,"RadDropDownList") == 0 */
/*           ) */
/*     { */
/*       t1 = "if(%s.Items != null)\n%s.Items.Clear();\n"; */
/*       sprintf(prefix,"%s %s %s",start,t1,end); */
/*       printf(prefix,name,name,name,name,name); */
/*     } */
  else
    {
      sprintf(prefix,"%s %s %s",start,end1,end2);
      printf(prefix,name,name,name);      
    }
  
  cleanStack();
}

// Test Case for these functions.
int main_push(int argc,char **argv)
{
  push("RadMenuItem");  
  push("abc");
  PrintStatement();
  return 0;
}
